package chapter8;

import java.util.Scanner;

/**
 * 转圈打印数组，额外空间复杂度O(1)
 */
public class SpiralOrderPrintMatrix {
    public static void spiralOrderPrint(int[][] matrix) {
        int tR = 0;
        int tC = 0;
        int dR = matrix.length - 1;
        int dC = matrix[0].length - 1;
        while (tR <= dR && tC <=dC) {
            printEdge(matrix, tR++, tC++, dR--, dC--);
        }
    }

    // 最后一个后面多一个空格
    private static void printEdge(int[][] matrix, int tR, int tC, int dR, int dC) {
        if (tR == dR) { // 矩阵只有一行
            for (int i = tC; i <= dC; ++i) {
                System.out.print(matrix[tR][i] + " ");
            }
        } else if (tC == dC) { // 矩阵只有一列
            for (int i = tR; i <= dR; ++i) {
                System.out.print(matrix[i][tC] + " ");
            }
        } else { // 普通情况
            int curC = tC;
            int curR = tR;
            while (curC != dC) { // 打印上行
                System.out.print(matrix[tR][curC++] + " ");
            }
            while (curR != dR) { // 打印右列
                System.out.print(matrix[curR++][dC] + " ");
            }
            while (curC != tC) { // 打印下行
                System.out.print(matrix[dR][curC--] + " ");
            }
            while (curR != tR) { // 打印左列
                System.out.print(matrix[curR--][tC]+ " ");
            }
        }
    }


    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[][] matrix = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
        spiralOrderPrint(matrix);
    }
}
